<?php
// +----------------------------------------------------------------------
// | Copyright (c) 2015 http://www.youdi365.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author:  心云间、凝听 <981248356@qq.com>
// +----------------------------------------------------------------------
namespace Cms\Controller;
use Admin\Controller\AdminController;

use Admin\Builder\AdminFormBuilder;
use Admin\Builder\AdminListBuilder;
class AdminCmsController extends AdminController {
    protected $postModel;
    protected $termsModel;
    function _initialize()
    {
        parent::_initialize();
        $this->postModel = D('Posts');
        $this->termsModel = D('Admin/terms');
        //实例化terms
        $this->post_category=$this->termsModel->getList(array('taxonomy'=>'post_category'));
        $this->post_tags=$this->termsModel->getList(array('taxonomy'=>'post_tag'));

    }
    //文章管理
    public function index($cid=0){
        $this->meta_title ='文章管理';
        if($cid){
            $post_ids=M('term_relationships')->where(array('term_id'=>$cid,'table'=>'posts'))->select();
            if(count($post_ids)){
                $post_ids=array_column($post_ids,'object_id');
                //$post_ids=array_merge(array($post_ids),$post_ids);
                $map['id']=array('in',$post_ids);
            }
        }
        // 获取所有文章
        $map['status'] = array('egt', '0'); // 禁用和正常状态
        $map['type']='post';
        $paged=I('get.p/d',1);
        list($data_list,$totalCount) = $this->postModel->getListByPage($map,$paged,'create_time desc','*',20);
        //遍历posts遍历的数据
        foreach($data_list as $k=>$post){
            $data_list[$k]['category_name']=get_term_info($post['id'],'name')['name']?:'暂无';//获得term名称
            $data_list[$k]['author']=get_user_info($post['author_id'])['nickname'];//获取用户名
        }
        $optCategory=$this->post_category;//获取所有分类
        foreach($optCategory as &$val){
            $val['id']=$val['term_id'];
            $val['value']=$val['name'];
        }
        unset($val);

            //构造移动文档的目标分类列表
            $options = '';
            foreach ($optCategory as $key => $val) {
                $options .= '<option value="'.$val['id'].'">'.$val['name'].'</option>';
            }
            //文档移动POST地址
            $move_url = U('moveCategory');
            //移动按钮属性
            $move_attr['title'] = '移 动';
            $move_attr['class'] = 'btn btn-info btn-raised btn-sm';
            $move_attr['onclick'] = 'move()';
            $extra_html = <<<EOF
            <div class="modal fade mt100" id="moveModal">
                <div class="modal-dialog modal-sm">
                    <div class="modal-content">
                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">关闭</span></button>
                            <p class="modal-title">移动至</p>
                        </div>
                        <div class="modal-body">
                            <form action="{$move_url}" method="post" class="form-move">
                                <div class="form-group">
                                    <select name="to_cid" class="form-control">{$options}</select>
                                </div>
                                <div class="form-group">
                                    <input type="hidden" name="ids">
                                    <input type="hidden" name="from_cid" value="{$cid}">
                                    <button class="btn btn-primary btn-raised btn-block submit ajax-post" type="submit" target-form="form-move">确 定</button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
            <script type="text/javascript">
                function move(){
                    var ids = '';
                    $('input[name="ids[]"]:checked').each(function(){
                       ids += ',' + $(this).val();
                    });
                    if(ids != ''){
                        ids = ids.substr(1);
                        $('input[name="ids"]').val(ids);
                        $('.modal-title').html('移动选中的的文章至：');
                        $('#moveModal').modal('show', 'fit')
                    }else{
                        updateAlert('请选择需要移动的文章', 'warning');
                    }
                }
            </script>
EOF;


        $builder = new AdminListBuilder();
        $builder->setMetaTitle('文章管理') // 设置页面标题
            ->addTopButton('addnew')  // 添加新增按钮
            ->addTopButton('resume',array('model'=>'posts'))  // 添加启用按钮
            ->addTopButton('forbid',array('model'=>'posts'))  // 添加禁用按钮
            ->addTopButton('recycle',array('model'=>'posts')) //添加回收按钮
            ->addTopButton('self', $move_attr) //添加移动按钮
            ->addSelect('分类','cid',array_merge(array(array('id'=>0,'value'=>'全部分类')),$optCategory))//添加分类筛选
            //->addSelect('作者','author_id',array_merge(array(array('id'=>0,'value'=>'所有作者')),$optCategory))//添加分类筛选
            ->setSearch('搜索文章')
            ->keyListItem('id', 'ID')
            ->keyListItem('title', '标题','link',U('edit',array('id'=>'__data_id__')))
            ->keyListItem('category_name','分类')
            ->keyListItem('views','浏览量')
            ->keyListItem('author','作者','author')
            ->keyListItem('create_time','发布时间', 'time')
            ->keyListItem('status', '状态', 'status')
            ->keyListItem('right_button', '操作', 'btn')
            ->setListDataKey('id')
            ->setListData($data_list)    // 数据列表
            ->setListPage($totalCount,20) // 数据列表分页
            ->setExtraHtml($extra_html)
            ->addRightButton('edit')          // 添加编辑按钮
            ->display();
    }
    //编辑
    public function edit($id=0){
        $title=$id?"编辑":"新增";
        $this->hide_panel =true;//隐藏base模板面板
        $this->meta_title =$title.'文章';

        $posta=$this->postModel->find($id);
        $this->assign('posta',$posta);
        $this->assign('category_id',get_the_category($id));
        $this->assign('form_url',U('edit',array('id'=>$id)));
        //修改
        if(IS_POST){
            if ($id) {
               $data['id']=$id;
            }
            $data['author_id']=$this->uid;
            $data['type']='post';
            $data['title']=I('post.title');
            $data['content']=htmlspecialchars_decode(I('post.content'));
            $data['img']=I('post.img/d');
            $data['status']=I('post.status/d');
            //$data['fields']=I('fields');
            if($this->postModel->create($data)){
                $result = $this->postModel->editData($data);
                if($result){
                    update_post_term($id,I('post.category_id/d',false));
                    $this ->success($title.'成功',U('index'));
                }else{
                    $this ->error($title.'失败');
                }
            }else{
                $this ->error($this->postModel->getError());
            }
            return;
        }
        $this->display();
    }

    //页面
    public function page(){
        $this->meta_title ='页面管理';
        // 获取所有文章
        $map['status'] = array('egt', '0'); // 禁用和正常状态
        $map['type']='page';
        $paged=I('get.p/d',1);
        list($data_list,$totalCount) = $this->postModel->getListByPage($map,$paged,'create_time desc','*',20);
        //遍历posts遍历的数据
        foreach($data_list as $k=>$page){
            $data_list[$k]['author']=get_user_info($page['author_id'])['nickname'];//获取用户名
        }
        // 使用Builder快速建立列表页面。
        $builder = new AdminListBuilder();
        $builder->setMetaTitle('页面管理') // 设置页面标题
                ->addTopButton('addnew',array('href'=>U('page_edit')))  // 添加新增按钮
                ->addTopButton('recycle',array('model'=>'posts'))  // 添加删除按钮
                ->setSearch('搜索页面', U('page'))
                ->keyListItem('title', '标题')
                ->keyListItem('views','浏览量')
                ->keyListItem('author','作者','author')
                ->keyListItem('create_time','发布时间', 'time')
                ->keyListItem('status', '状态', 'status')
                ->keyListItem('right_button', '操作', 'btn')
                ->setListDataKey('id')
                ->setListData($data_list)    // 数据列表
                ->setListPage($totalCount,20) // 数据列表分页
                ->addRightButton('edit',array('href'=>U('page_edit',array('id'=>'__data_id__'))))  // 添加编辑按钮
                ->addRightButton('recycle')        // 添加删除按钮
               ->display();
    }
    /**
     * 编辑页面
     * @author 
     */
    public function page_edit($id=0) {
        $title=$id?"编辑":"新增";
        if (IS_POST) {
            $data = $this->postModel->create();
            if($data){
                $result = $this->postModel->editData($data);
                if ($result) {
                    $this->success($title.'成功', U('page'));
                } else {
                    $this->error($title.'失败');
                }
            }else{
                $this->error($this->postModel->getError());
            }
        }else {
            if ($id!=0) {
               $page_data =$this->postModel->find($id);
            }
            
            $builder = new AdminFormBuilder();
            $builder->setMetaTitle($title.'页面') //设置页面标题
                    ->addFormItem('title', 'text', '标题')
                    ->addFormItem('content', 'ueditor', '内容')
                    ->addFormItem('type','hidden')
                    ->addFormItem('author_id', 'number', '作者', '')
                    ->addFormItem('seo_keywords', 'text', 'SEO关键字', '')
                    ->setFormData($page_data)
                    ->addButton('submit')->addButton('back')    // 设置表单按钮
                    ->display();
        }
    }
    /**
     * 移动分类
     */
    public function moveCategory() {
        if (IS_POST) {
            $ids = I('post.ids');
            $from_cid = I('post.from_cid');
            $to_cid = I('post.to_cid');
            if ($from_cid === $to_cid) {
                $this->error('目标分类与当前分类相同');
            }
            if ($to_cid) {
                $map['object_id'] = array('in',$ids);
                $data = array('term_id' => $to_cid);
                $this->editRow('term_relationships', $data, $map, array('success'=>'移动成功','error'=>'移动失败',U('index')));

            } else {
                $this->error('请选择目标分类');
            }
        }
    }
    /**
     * 编辑页面
     * @author 心云间、凝听 <981248356@qq.com> 
     */
    function trash(){
        $this->meta_title ='回收站';
        // 获取所有文章
        $map['status'] = array('in',array(-1,0)); // 禁用和正常状态
        $paged=I('get.p/d',1);
        list($data_list,$totalCount) = $this->postModel->getListByPage($map,$paged,'create_time desc','*',20);
        //遍历posts遍历的数据
        foreach($data_list as $k=>$page){
            $data_list[$k]['category_name']=get_term_info($page['id'],'name')['name']?:'暂无';//获得term名称
            $data_list[$k]['author']=get_user_info($page['author_id'],'nickname');//获取用户名
        }
        // 使用Builder快速建立列表页面。
        $builder = new AdminListBuilder();
        $builder->setMetaTitle('回收站') // 设置页面标题
                ->addTopButton('restore',array('model'=>'posts'))  // 添加启用按钮
                ->addTopButton('delete',array('model'=>'posts'))  // 添加删除按钮
                ->setSearch('输入标题')
                ->keyListItem('title', '标题')
                ->keyListItem('category_name','分类')
                ->keyListItem('type','类型')
                ->keyListItem('author','作者','author')
                ->keyListItem('create_time','发布时间', 'time')
                ->keyListItem('status', '状态', 'status')
                ->keyListItem('right_button', '操作', 'btn')
                ->setListDataKey('id')
                ->setListData($data_list)    // 数据列表
                ->setListPage($totalCount,20) // 数据列表分页
                ->addRightButton('edit',array('href'=>U('page_edit',array('id'=>'__data_id__'))))  // 添加编辑按钮
                ->addRightButton('delete')  // 添加删除按钮
               ->display();
    }
    /**
     * 设置一条或者多条数据的状态
     */
    public function setStatus($model = 'Posts') {
        $ids    = I('request.ids');
        $status = I('request.status');
        if (empty($ids)) {
            $this->error('请选择要操作的数据');
        }
        $map['id'] = array('in',$ids);
        switch ($status) {
            case 'delete' :  // 删除条目
                $map['status'] = -1;
                $exist = $this->postModel->where($map)->find();
                if ($exist) {
                    $result = $this->postModel->delete($ids);
                } else {
                    $result = true;
                }
                if ($result) {
                    $result2 = $this->postModel->delete($ids);
                    if ($result2) {
                        $this->success('彻底删除成功');
                    } else {
                        $this->error('删除失败');
                    }
                } else {
                    $this->error('删除失败');
                }
                break;
            default :
                parent::setStatus($model);
                break;
        }
    }
}